use std::thread;
use std::sync::{mpsc, Arc, Mutex};
use std::time::Duration;

fn do_threading() {
    let handle = thread::spawn(|| {
        println!("线程运行中");
    });
    handle.join().unwrap();
    println!("线程运行完成");
}


fn do_atomic_ref() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("计数: {}", *counter.lock().unwrap());
}

fn do_producer_vs_consumer() {
    // 创建通道 类似LinkBlockQueue
    let (tx, rx) = mpsc::channel();
    // 生产者
    let producer = thread::spawn(move || {
        for i in 0..5 {
            println!("推送 {}", i);
            tx.send(i).unwrap();
            thread::sleep(Duration::from_millis(500));
        }
    });
    // 消费者
    let consumer = thread::spawn(move || {
        for _ in 0..5 {
            let received = rx.recv().unwrap();
            println!("接收 {}", received);
        }
    });
    producer.join().unwrap();
    consumer.join().unwrap();
}

fn main() {
    do_threading();
    do_atomic_ref();
    do_producer_vs_consumer();
}
